package com.llk.myIoLearn.reactorBase.myreactor.v2;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

public class Process {
    static void handleRead(SelectionKey key) {
        try {
            SocketChannel client = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int bytesRead = client.read(buffer);

            if (bytesRead == -1) {
                key.cancel();
                return;
            }

            buffer.flip();
            String request = new String(buffer.array(), 0, bytesRead);
            System.out.println("收到请求：" + request);

            // 生成响应数据
            String response = buildResponse(request);
            key.attach(response);
            key.interestOps(SelectionKey.OP_WRITE);  // 注册写事件[7](@ref)
            key.selector().wakeup();  // 唤醒主线程处理写事件
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String buildResponse(String msg) {
        String body = "ECHO: " + msg;
        return "HTTP/1.1 200 OK\r\n" +
                "Content-Type: text/plain\r\n" +
                "Content-Length: " + body.length() + "\r\n" +
                "\r\n" + body;
    }
    static void handleWrite(SelectionKey key) {
        SocketChannel client = null;
        try {   
            client= (SocketChannel) key.channel();
            String response = (String) key.attachment();
            ByteBuffer buffer = ByteBuffer.wrap(response.getBytes());
            client.write(buffer);

            // 重置为读事件监听
            key.interestOps(SelectionKey.OP_READ);
            key.attach(null);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                client.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
